//
//  SXMainViewController.swift
//  微博09项目
//
//  Created by mac on 15/9/1.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class SXMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        addChildViewControllers()
        
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        composeButtonOfFrame()
    }
   private func addChildViewControllers() {
    
        addChildViewController(SXHomeViewController(), title: "首页", nameString: "tabbar_home")
        addChildViewController(SXMessageViewController(), title: "消息", nameString: "tabbar_message_center")
        
        // 添加了一个空白的控制器
        addChildViewController(UIViewController())
        
        addChildViewController(SXDiscoverViewController(), title: "发现", nameString: "tabbar_discover")
        addChildViewController(SXProfileViewController(), title: "我", nameString: "tabbar_profile")
    }
    //mark : 添加子控制器
  private func addChildViewController(vc:UIViewController,title:String,nameString:String) {
        //设置导航控制器的的title
        vc.title = title
    
        vc.tabBarItem.image = UIImage(named: nameString)
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
        
    }
    //这个方法不能写成私有方法，如果写成私有方法，控制器访问不到
    func clickComposedButton(){
       // print(__FUNCTION__)
        let vc:UIViewController
       
        if UserAccountViewModel.shareUserAccount.userLogon{
            vc = SXComposeViewController()
        }else{
            vc = SXOauthController()
        }
        
        let nav = UINavigationController(rootViewController: vc)
       
        presentViewController(nav, animated: true, completion: nil)
        
    }
//   mark:懒加载控件
    private var composedButton:UIButton{
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        tabBar.addSubview(btn)
        btn.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
        
    }
    //设置Button的frame
    private func composeButtonOfFrame() {
        let btn = composedButton
        
        let count = childViewControllers.count
        let w = tabBar.frame.width/CGFloat(count)
        let rect = CGRect(x: 0, y: 0, width: w , height: tabBar.frame.height)
        
        btn.frame = CGRectOffset(rect, 2 * w, 0)
    }
    

}
